package com.ilarele.shopping.client.adaptors;

import android.util.Log;

import com.ilarele.shopping.Product;
import com.ilarele.shopping.ProductLocation;

public class ProductComparatorLocation extends ProductComparator {
	private static final int R = 6371;
	private ProductLocation mReferencePoint;

	public ProductComparatorLocation(ProductLocation fixPoint) {
		mReferencePoint = fixPoint;
	}

	@Override
	protected int getComparedValue(Product p1, Product p2) {
		if (mReferencePoint.name.equals("none")) {
			Log.d("log", "Default Location isn't set");
			return 0;
		}
		double d1 = getDistance(p1.pInfo.pLocation, mReferencePoint);
		double d2 = getDistance(p2.pInfo.pLocation, mReferencePoint);
		return Double.compare(d1, d2);
	}

	private static double getDistance(ProductLocation p1, ProductLocation p2) {
		double lat1 = Math.toRadians(p1.latitude);
		double long1 = Math.toRadians(p1.longitude);
		double lat2 = Math.toRadians(p2.latitude);
		double long2 = Math.toRadians(p2.longitude);

		double dLat = lat2 - lat1;
		double dLon = long2 - long1;

		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
				* Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double distance = R * c;

		return distance;
	}

}
